package com.newcapec.servlet;

import com.newcapec.bean.ColumnEntity;
import com.newcapec.bean.NewsEntity;
import com.newcapec.bean.Page;
import com.newcapec.dao.ColumnDao;
import com.newcapec.dao.NewsDao;
import com.newcapec.dao.impl.ColumnDaoImpl;
import com.newcapec.service.NewsService;
import com.newcapec.service.impl.NewsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Author:yangshupeng
 * @Date: 2022/3/21 22:04
 * @Version:1.0
 */
@WebServlet("/showNews")
public class ShowNewsHtmlServlet extends HttpServlet {
    //设置当前页默认为第一页
    private  int pageNum1 = 1;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求和响应的内容的编码格式
        /*req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");*/
        /*resp.setContentType("text/html;charset=utf-8");*/

        //创建page实例对象
        Page page = new Page();
        NewsService newsService = new NewsServiceImpl();

        //获取按钮点击的当前页数
        String pageNum = req.getParameter("pageNum");
        //获取模糊查询输入的标题
        String title = req.getParameter("title");
        //设置查询到的数据的总条数到page对象中
        page.setTotal(newsService.getAllCount(title));

        NewsEntity newsEntity = new NewsEntity();
        newsEntity.setTitle(title);

        //获取修改后当前的页数
        String pageNum1 = (String) req.getSession().getAttribute("pageNum");
        if (pageNum1 != null){
            this.pageNum1 = Integer.parseInt(pageNum1);
        }

        //设置当前页
        if (pageNum != null){

            page.setPageNum(Integer.parseInt(pageNum));
        }else {

            page.setPageNum(this.pageNum1);
        }
        //设置每页展示几条数据
        page.setPageSize(7);

        List<NewsEntity> newsEntityList;
        if (title != null){
            newsEntityList = newsService.query(page.getOffset(),page.getPageSize(),newsEntity);
        }else {
            newsEntityList = newsService.query(page.getOffset(),page.getPageSize(),null);
        }

        req.setAttribute("page",page);
        if (newsEntityList.size() != 0){
            req.setAttribute("newsList",newsEntityList);
        }else {
            req.setAttribute("msg","抱歉！没有您要找的新闻数据！赶快发布吧！");
        }

        req.setAttribute("title",title);

        //请求转发
        req.getRequestDispatcher("WEB-INF/jsp/NewsManagement.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
